package com.europe.business.europebusiness.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.europe.business.europebusiness.R;
import com.europe.business.europebusiness.ui.activity.base.ActionBarActivity;
import com.europe.business.europebusiness.ui.adapter.ListAdapter;
import com.europe.business.europebusiness.ui.adapter.MultiItemTypeSupport;
import com.europe.business.europebusiness.ui.adapter.MutilItemCommonAdapter;
import com.europe.business.europebusiness.ui.adapter.viewholder.ListViewHolder;
import com.europe.business.europebusiness.ui.bean.BaseDataBean;
import com.europe.business.europebusiness.ui.bean.CompanyCategoryBean;
import com.europe.business.europebusiness.ui.bean.CountryBean;
import com.europe.business.europebusiness.ui.bean.ICommonList;
import com.europe.business.europebusiness.ui.common.Commons;
import com.europe.business.europebusiness.ui.net.ICompany;
import com.europe.business.europebusiness.ui.utils.Utils;
import com.europe.business.europebusiness.ui.view.ListScrollerListener;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ListActivity1<E extends BaseDataBean, T extends ICommonList> extends ActionBarActivity implements ListAdapter.ItemClicked {
    private static final String TAG = "ListActivity";
    private RecyclerView recyclerView;
    List<CompanyCategoryBean.Data> list;
    public static final int FALG_COUNTRY = 11;
    public static final int FALG_CITY = 12;
    public static final int FALG_SORT = 13;
    List<CountryBean.Country> countryList;
    protected static final int PAGE_SIZE = 20;
    private int pageNum = 1;
    private int flag;
    MutilItemCommonAdapter mutilItemCommonAdapter;

    enum ListMoreStuts {
        LOADING,//加载中
        LOADED,//一次加载完成
        LOAD_COMPLETED, //已经到底
        LOAD_FAILURE //加载失败
    }

    ListMoreStuts moreStuts;
    List<T> listData;
    E beanData;

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    protected void updateOnFailure() {
        moreStuts = ListMoreStuts.LOAD_FAILURE;
        setIsHaveFootItem(true);
        if (null != mutilItemCommonAdapter) {
            mutilItemCommonAdapter.notifyDataSetChanged();
        }
        showToastLong(getString(R.string.requst_failed));
    }


    /**
     * 下拉刷新时更新界面
     *
     * @param beanData
     */

    protected void refrshRecycleViewDownPullOnResponse(E beanData) {
        updateRecycleViewOnResponse(beanData, true);
    }

    /**
     * 上拉加载更多时更新界面
     *
     * @param beanData
     */
    protected void refrshRecycleViewUpPullOnResponse(E beanData) {
        updateRecycleViewOnResponse(beanData, false);
    }

    /**
     * 有响应的时候更新Recycle界面.
     *
     * @param beanData
     */
    public void updateRecycleViewOnResponse(E beanData, boolean isDownPull) {
        setIsHaveFootItem(true);//一定有footItem
        if (null != beanData) {
            if (beanData.getErrorCode() == 1) {
                List<T> data = beanData.getData();
                if (isDownPull) {//下拉刷新
                    listData = data;
                } else {//上拉更多
                    if (listData.size() == 0) {
                        listData = data;
                    } else {
                        listData.addAll(data);
                    }
                }

                MultiItemTypeSupport<T> multiItemTypeSupport = new MultiItemTypeSupport<T>() {
                    @Override
                    public int getLayoutId(int type) {
                        if (type == MutilItemCommonAdapter.VIWE_TYPE_DATA) {
                            return R.layout.activity_text_item;
                        } else {
                            return R.layout.item_foot_company;
                        }
                    }

                    @Override
                    public int getItemViewType(int position) {
                        if (position == listData.size()) {
                            return MutilItemCommonAdapter.VIWE_TYPE_FOOT;
                        } else {
                            return MutilItemCommonAdapter.VIWE_TYPE_DATA;
                        }
                    }
                };
                moreStuts = ListMoreStuts.LOADED;
                if (mutilItemCommonAdapter == null) {
                    mutilItemCommonAdapter = new MutilItemCommonAdapter<T>(ListActivity1.this, listData, multiItemTypeSupport, ListActivity1.this) {
                        @Override
                        public void convert(ListViewHolder holder, T o) {
                            if (o == null) {
                                ProgressBar progressBar = holder.getView(R.id.progress);
                                //得到文本textview
                                TextView tv = holder.getView(R.id.loading);
                                switch (moreStuts) {
                                    case LOADED:
                                        progressBar.setVisibility(View.GONE);
                                        tv.setText(getString(R.string.load_over));
                                        break;
                                    case LOADING:
                                        progressBar.setVisibility(View.VISIBLE);
                                        tv.setText(getString(R.string.loading));
                                        break;

                                    case LOAD_FAILURE:
                                        progressBar.setVisibility(View.GONE);
                                        tv.setText(getString(R.string.load_failure));
                                        break;

                                    case LOAD_COMPLETED:
                                        progressBar.setVisibility(View.GONE);
                                        tv.setText(getString(R.string.loaded));
                                        break;
                                }
                            } else {
                                bindView(holder, o);
//                                TextView  tv = holder.getView(R.id.tv);
//                                tv.setText(o.getName());
                            }


                        }

                    };
                    recyclerView.setAdapter(mutilItemCommonAdapter);

                } else {
                    mutilItemCommonAdapter.notifyDataSetChanged();
                }

            } else {
                if (beanData.getErrorCode() == 1003) {//没有更多数据
                    moreStuts = ListMoreStuts.LOAD_COMPLETED;
                    showToastLong(getString(R.string.info_list_no_more_data));
                    if (pageNum == 1) {//如果第一页就没有数据，清空数据而且不显示页脚
                        if (mutilItemCommonAdapter != null) {
                            listData.clear();
                            setIsHaveFootItem(false);
                            mutilItemCommonAdapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    moreStuts = ListMoreStuts.LOAD_FAILURE;
                    showToastLong(beanData.getErrorMessage());
                }
                if (null != mutilItemCommonAdapter) {
                    mutilItemCommonAdapter.notifyDataSetChanged();
                }
            }

        } else {
            moreStuts = ListMoreStuts.LOAD_FAILURE;
            if (null != mutilItemCommonAdapter) {
                mutilItemCommonAdapter.notifyDataSetChanged();
            }
            showToastLong(getString(R.string.requst_failed));
        }
    }

    protected void bindView(ListViewHolder holder, T o){
        TextView tv = holder.getView(R.id.tv);
        if(tv != null){
            tv.setText(o.getItemContent());
        }
    }

    @Override
    protected int setMainContent() {
        return getLayoutId();
    }


    @Override
    protected void initView() {
        super.initView();
        recyclerView = findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setOnScrollListener(new ListScrollerListener() {
            @Override
            public void onPageNext() {
                Log.e(TAG, "------onPageNext------");
                if (moreStuts == ListMoreStuts.LOAD_COMPLETED || moreStuts == ListMoreStuts.LOADING) {
                    return;
                }
                int dataCount = mutilItemCommonAdapter.getDataCount();
                setIsHaveFootItem(true);
                moreStuts = ListMoreStuts.LOADING;
                mutilItemCommonAdapter.notifyDataSetChanged();
                recyclerView.scrollToPosition(dataCount);

                //调用接口，请求数据
                pageNum++;
                getData(pageNum, PAGE_SIZE);
            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
        countryList = new ArrayList<CountryBean.Country>();
        flag = getIntent().getIntExtra("flag", -1);
        if (isInitToGetData()) {
            getData(pageNum, PAGE_SIZE);
        }

    }

    /**
     * 子类初始化data时必须重写该方法获取数据
     */
    protected void getData(int pageNum, int pageSize) {

    }


    protected boolean isInitToGetData(){
        return true;
    }

    /**
     * 设置是否显示底部加载更多item
     * @param isHaveFootItem
     */
    protected void setIsHaveFootItem(boolean isHaveFootItem){

        if(null != mutilItemCommonAdapter){
            if(isHaveFootItem){
                mutilItemCommonAdapter.setIsHaveFoot(1);
            }else{
                mutilItemCommonAdapter.setIsHaveFoot(0);
            }
        }
    }


    protected Callback<E> getCallback(){
        Callback<E> callback = new Callback<E>() {
            @Override
            public void onResponse(Call<E> call, Response<E> response) {

                dismissProgressDialog();
                E bean = response.body();
                if (pageNum == 1) {//第一页，一定是在下拉刷新
                    refrshRecycleViewDownPullOnResponse(bean);
                } else {//第二页，一定是在上拉加载更多
                    refrshRecycleViewUpPullOnResponse(bean);
                }
            }

            @Override
            public void onFailure(Call<E> call, Throwable t) {
                Log.e("ListActivity", t.getMessage());
                dismissProgressDialog();
                updateOnFailure();
            }
        };
        return callback;
    }

    @Override
    public void onItemClicked(int index) {
        T t = listData.get(index);
        Intent intent = new Intent();
        intent.putExtra("data", t);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
    /**
     *  子类实现该方法，传给父类布局ID,以覆盖父类此方法
     * @return
     */
    protected int getLayoutId(){
        return R.layout.activity_info_select_list;
    }
    /**
     *  子类实现该方法，传给父类RecyvleView,以覆盖父类此方法
     * @return
     */
    protected  <T extends View> T getRecycleView(){
        return findViewById(R.id.rv);
    }

}
